package utils;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.xiaoleilu.hutool.Log;
import com.xiaoleilu.hutool.StrUtil;
import bean.Request;
import bean.Response;

public class CommonUtil {
	public static String resp2Str(Response resp){
		StringBuilder sb = new StringBuilder();
		sb.append(resp.getHttpVersion()+" ");
		sb.append(resp.getStatusCode()+" ");
		sb.append(resp.getStatus()+"\r\n");
		Map header = resp.getHeaderData();
		for(Iterator iterator =header.entrySet().iterator() ; iterator.hasNext() ; ){
			Entry<String,Object> entry = (Entry<String, Object>) iterator.next();
			sb.append(entry.getKey()+":"+entry.getValue()+"\r\n");
		}
		sb.append("\r\n");
		return sb.toString();
	}
	
	public static Request str2Req(String reqStr){
		if(StrUtil.isEmpty(reqStr)){
			return null;
		}
		Request req = new Request();
		String[] reqArray = reqStr.split("\r\n");
		String[] arr = reqArray[0].split(" ");//第一行请求数据
		req.setMethod(arr[0]);
		if(arr[1].contains("?")){
			String url = arr[1].substring(0,arr[1].indexOf("?"));//url 和 parameter
			req.setUrl(url);
		}else
			req.setUrl(arr[1]);
		
		String[] pv = arr[2].split("/");//协议和版本
		req.setProtocol(pv[0]);
		req.setVersion(pv[1]);
		if("GET".equals(req.getMethod())){
			if(arr[1].contains("?")){
				String paraStr = arr[1].substring(arr[1].indexOf("?")+1);//url 和 parameter
				String[] paras = paraStr.split("&");
				for(String para : paras){
					String[] kv = para.split("=");
					req.setParameter(kv[0], kv[1]);
				}
			}else{
				req.setUrl(arr[1]);
			}
			
			for(int i = 1 ; i < reqArray.length ; i++){
				String[] ha = reqArray[i].split(":");
				req.setHeader(ha[0], ha[1]);
			}
		}
		if("POST".equals(req.getMethod())){
			String body = reqArray[reqArray.length-1];
			String[] paras = body.split("&");
			for(String para : paras){
				String[] kv = para.split("=");
				if(req.containsParaName(kv[0])){
					if(req.getParameter(kv[0]) != null){
						
					}
				} else
					req.setParameter(kv[0], kv[1]);
			}
			Log.info("body="+body);
		}
		return req;
	}
	public static String req2Str(Request req){
		StringBuilder sb = new StringBuilder();
		sb.append(req.getMethod()+" ");
		sb.append(req.getUrl()+" ");
		sb.append(req.getProtocol()+"/"+req.getVersion()+"\r\n");
		
		Map header = req.getHeaderData();
		for(Iterator iterator =header.entrySet().iterator() ; iterator.hasNext() ; ){
			Entry<String,Object> entry = (Entry<String, Object>) iterator.next();
			sb.append(entry.getKey()+":"+entry.getValue()+"\r\n");
		}
		sb.append("\r\n");
		sb.append(req.getBody());
		return sb.toString();
	}
	public static void printArray(String[] sa){
		for(String s : sa){
			Log.info(s);
		}
	}
}
